package com.dhp.Utils;

import com.dhp.constant.GenChartConstant;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.google.common.base.Predicates;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RetryUtil {
    @Autowired
    private AIUtil aiUtil;

    @SneakyThrows
    public String retryChart(String userRequest){
        // 创建相应的retry规则
        //定义重试机制
        Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
                //retryIf 重试条件
                .retryIfException()
                .retryIfRuntimeException()
                .retryIfExceptionOfType(Exception.class)
                .retryIfException(Predicates.equalTo(new Exception()))
                //如果返回为""重试
                .retryIfResult(Predicates.equalTo(""))

                //等待策略：每次请求间隔1s
                //fixedWait 固定X秒后重试
                //noWait不等时间直接重试
                //incrementingWait 第一个参数为第一次重试时间，后面会通过设置间隔递增秒数重试
                //randomWait 随机等待设置范围内的时间重试
                .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))

                //停止策略 : 尝试请求3次
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                .build();

        //定义请求实现
        Callable<String> callable = new Callable<String>() {
            int times = 1;

            @Override
            public String call() throws Exception {
                log.info("重试调用={}", times);
                times++;
                String ans = aiUtil.doChat(userRequest);
                if (StringUtils.isEmpty(ans)){
                    throw new Exception();
                }
                //将回答拆分
                String[] split = ans.split(GenChartConstant.AI_CHART_SPILT);
                if (split.length != 3){
                    return "";
                }
                return ans;
            }
        };
        return retryer.call(callable);
    }

}
